﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


/**
 * 委托应用：模板方法
 */
namespace P19_4 {
    internal class Program {
        static void Main(string[] args) {

            ProductFactory productFactory = new ProductFactory();
            WrapFactory wrapFactory = new WrapFactory();
            //委托
            Func<Product> fun1 = new Func<Product>(productFactory.MakePizza);
            Func<Product> fun2 = new Func<Product>(productFactory.MakeToyCar);

            Logger logger = new Logger();
            //Action：这是一个带有一个输入参数的委托
            Action<Product> log1 = new Action<Product>(logger.Log); 
            Action<Product> log2 = new Action<Product>(logger.Log);
            Box box1 = wrapFactory.WrapProduct(fun1, log1);
            Box box2 = wrapFactory.WrapProduct(fun2, log2);
            Console.WriteLine(box1.Prod.Name);
            Console.WriteLine(box2.Prod.Name);
            Console.ReadLine();
        }
    }

    class Logger {
        public void Log(Product prod) { 
            Console.WriteLine("Product '{0}' created {1}. Price is {2}.",prod.Name,DateTime.UtcNow,prod.Price);
        }
    }
    class Product {
        public string Name { get; set; }
        public double Price { get; set; }
    }
    class Box {
        public Product Prod { get; set; }
    }
    class WrapFactory {
        public Box WrapProduct(Func<Product> getProduct,Action<Product> logCallback) {
            Box box = new Box();
            Product product = getProduct.Invoke();
            if (product.Price > 50) {
                //这里需要把 product 传递到委托中是因为创建的 Action<in T> 委托就有一个输入参数
                //实例：Action<Product> log1 = new Action<Product>(logger.Log); 
                logCallback(product);
            }
            box.Prod = product;
            return box;
        }
    }

    class ProductFactory {
        public Product MakePizza() {
            Product product = new Product();
            product.Name = "Pizza";
            product.Price = 12;
            return product;
        }

        public Product MakeToyCar() {
            Product prod = new Product();
            prod.Name = "Toy Car";
            prod.Price = 100;
            return prod;
        }
    }
}
